<script lang="ts">
	// import { goto } from '$utils/intercept';
	import { page } from '$app/stores';
	import { goto } from '$utils/intercept';
	import Tab, { Icon, Label } from '@smui/tab';
	import TabBar from '@smui/tab-bar';
	import { debounce } from 'lodash-es';

	let tabs = [
		{
			icon: 'home',
			label: 'My Cart',
			path: '/cart'
		},
		{
			icon: 'widgets',
			label: 'Orders',
			path: '/order/list'
		},
		{
			icon: 'calendar_month',
			label: 'account',
			path: '/account'
		},
		{
			icon: 'perm_contact_calendar',
			label: 'Messages',
			path: '/message'
		}
	];

	type Tab = (typeof tabs)[number];

	let active: Tab = {} as Tab;

	const handleTabChange = () => goto(active.path);

	let currentUrl = '';
	const setActiveTab = debounce(() => {
		active =
			tabs.find((tab) => tab.path.includes($page.url.pathname.replace(/^\//g, '').split('/')[0])) ||
			tabs[2];
	}, 300);

	$: {
		// 使用$:监听page变化，
		// 但是在组件销毁的时候同样触发了一次
		const pathname = $page.url.pathname;
		if (pathname !== currentUrl) setActiveTab();
	}
</script>

<!-- 
		class="bg-gray-2 flex-cc"
		class="w-1320px min-w-350px max-w-100%" 
	-->
<TabBar
	class="reset-tab-color plus-indicator hidden-ripple"
	{tabs}
	let:tab
	bind:active
	on:click={handleTabChange}
>
	<Tab {tab} class="color-white!" indicatorSpanOnlyContent={true}>
		<Label>{tab.label}</Label>
	</Tab>
</TabBar>

<style>
</style>
